<template>
  <div ref="funnelChartRef" class="w-1/1 h-1/1"></div>
</template>
<script setup lang="ts">
import type { EChartsOption } from "echarts";
import echarts from "@/plugins/echarts";
const funnelChartRef = ref<ElRef>();
let echartRef: Nullable<echarts.ECharts> = null;

const props = defineProps({
  title: {
    type: String,
    default: "",
  },
  formatter: {
    type: String,
    default: "",
  },
  options: {
    type: Object,
    default() {
      return {};
    },
  },
});
watch(
  () => props.options,
  () => {
    setOptions();
  },
  { deep: true }
);

onMounted(() => {
  initChart();
});
onUnmounted(() => {
  echartRef?.dispose;
});
const initChart = () => {
  if (unref(funnelChartRef) && props.options) {
    echartRef = echarts.init(unref(funnelChartRef) as unknown as HTMLElement);
    setOptions();
    window.onresize = function () {
      echartRef?.resize();
    };
  }
};

const setOptions = () => {
  if (unref(funnelChartRef) && props.options) {
    const _legendData: string[] = [];

    if (props.options.seriesData && props.options.seriesData.length > 0) {
      props.options.seriesData.forEach((item: any) => {
        _legendData.push(item.name);
      });
    }

    const _echartOption: EChartsOption = {
      title: {
        text: props.title,
        left: "left",
      },
      tooltip: {
        trigger: "item",
        formatter: props.formatter,
      },

      legend: {
        top:"50px",
        orient: "vertical",
        left: "right",
        data: _legendData,
      },
      series: [
        {
          name: "",
          type: "funnel",
          left: "5%",
          top: 60,
          bottom: "20px",
          width: "70%",
          min: 0,
          max: 100,
          minSize: "10%",
          maxSize: "100%",
          sort: "descending",
          gap: 1,
          label: {
            show: true,
            position: "inside",
          },
          labelLine: {
            length: 10,
            lineStyle: {
              width: 1,
              type: "solid",
            },
          },
          itemStyle: {
            borderColor: "#fff",
            borderWidth: 1,
          },
          emphasis: {
            label: {
              fontSize: 20,
            },
          },
          data: props.options.seriesData,
        },
      ],
    };
    echartRef?.setOption(_echartOption);
  }
};
</script>
